package com.netnovelstore.controller;

import com.netnovelstore.annotation.NotNullAndBlank;
import com.netnovelstore.annotation.ResultInterceptor;
import com.netnovelstore.pojo.Exception.NotDataException;
import com.netnovelstore.pojo.Result;
import com.netnovelstore.pojo.User;
import com.netnovelstore.service.UserService;
import com.netnovelstore.viewObject.LoginResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.io.IOException;
import java.sql.SQLException;

@RestController
@CrossOrigin
@Api(tags = "用户接口")
@ResultInterceptor
@RequestMapping("/User")
@Slf4j
public class UserController {

    private UserService userServiceImpl;

    @Autowired
    public UserController(UserService userServiceImpl) {
        this.userServiceImpl = userServiceImpl;
    }

    @PostMapping("/login")
    @ApiOperation("登录验证")
    @NotNullAndBlank
    public Result<LoginResult> Login(@NotBlank String username, @NotBlank String password, HttpServletResponse response) throws IOException, NotDataException {
        return userServiceImpl.Login(username, password);
    }

    @PostMapping(value = "/uploadProfile")
    @ApiOperation("个人头像设置")
    @NotNullAndBlank
    public Result<String> uploadProfile(@RequestParam(value = "file", required = false) MultipartFile file, @RequestParam("oldUserImg") String oldUserImg, @RequestParam("username") String username, HttpServletResponse response) throws IOException {
        log.info("username => " + username);
        log.info("oldUserImg => " + oldUserImg);
        if (file == null || file.isEmpty()) {
            response.sendError(400);
        }
        return userServiceImpl.uploadProfile(file, oldUserImg, username);
    }

    @PostMapping(value = "/addProfile")
    @ApiOperation("个人头像预上传(注册)")
    @NotNullAndBlank
    public Result<String> addProfile(@RequestPart @RequestParam("file") MultipartFile file) throws IOException {
        log.info(file.getOriginalFilename());
        return userServiceImpl.addProfile(file);
    }


    @PutMapping("/register")
    @ApiOperation("注册用户")
    @NotNullAndBlank
    public Result userRegistered(@RequestBody User user) throws SQLException {
        log.info("register=>    " + user.toString());
        return userServiceImpl.userRegistered(user);
    }


    @NotNullAndBlank
    @GetMapping("/isExistByUserName")
    @ApiOperation("判断用户是否存在")
    public Result<Boolean> isExistByUserName(String userName) {
        return userServiceImpl.isExistByUserName(userName);
    }


}
